package com.sky.service.user.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.mapper.common.DishMapper;
import com.sky.mapper.common.SetmealMapper;
import com.sky.mapper.user.ShoppingCartMapper;
import com.sky.pojo.Setmeal;
import com.sky.pojo.ShoppingCart;
import com.sky.result.Result;
import com.sky.service.user.ShoppingCartService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {


    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    public Result<String> add(ShoppingCartDTO dto) {


        //1.判断当前用户购物车是否存在商品
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(dto,shoppingCart);
        shoppingCart.setUserId(BaseContext.getCurrentId()); //threadLocal中的用户id
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectByConditon(shoppingCart);
        if(shoppingCartList!=null&&shoppingCartList.size()==1){
            //1.1 存在，数量+1即可   10
            shoppingCartMapper.addNumberById(shoppingCartList.get(0).getId());
        }else{
            //1.2 不存在，新增
            //创建shoppingCart对象
            //填充shoppingCart对象的属性
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            if(dto.getSetmealId()!=null){
                //是套餐
                Setmeal setmeal = setmealMapper.getById(dto.getSetmealId());
                shoppingCart.setName(setmeal.getName());
                shoppingCart.setImage(setmeal.getImage());
                shoppingCart.setAmount(setmeal.getPrice());
            }else{
                //是菜品
                DishVO dishVO = dishMapper.selectDishWithFlavors(dto.getDishId());
                shoppingCart.setAmount(dishVO.getPrice());
                shoppingCart.setName(dishVO.getName());
                shoppingCart.setImage(dishVO.getImage());
            }
            //保存入库
            shoppingCartMapper.save(shoppingCart);
        }

        return Result.success();
    }

    @Override
    public Result<List<ShoppingCart>> list() {
        //查询当前用户的购物
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectByConditon(shoppingCart);
        return Result.success(shoppingCartList);
    }

    @Override
    public Result<String> clean() {


        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());

        return Result.success();
    }
}
